package com.glodon.paas.document.storage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.BeforeClass;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;

public class AbstractTestCase {

    protected static DataSource dataSource;
    protected static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() throws Exception {
        dataSource = createDataSource();
        sqlSessionFactory = createSqlSessionFactory();
    }

    public static <T> T createMapper(Class<T> clz) throws Exception {
        MapperFactoryBean<T> factoryBean = new MapperFactoryBean<T>();
        factoryBean.setSqlSessionFactory(sqlSessionFactory);
        factoryBean.setMapperInterface(clz);
        factoryBean.afterPropertiesSet();
        return factoryBean.getObject();
    }

    private static BasicDataSource createDataSource() throws ClassNotFoundException, SQLException {
        initDatabase();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/paas_storage");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

    private static SqlSessionFactory createSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.afterPropertiesSet();
        return sqlSessionFactoryBean.getObject();
    }

    private static void initDatabase() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "");
        Statement st = conn.createStatement();
        st.executeUpdate("CREATE DATABASE IF NOT EXISTS paas_storage CHARACTER SET utf8 COLLATE utf8_bin;");
        st.close();
        conn.close();
    }
}